package com.example.demo2.student;

import com.example.demo2.Util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.example.demo2.pojo.course;
import com.example.demo2.pojo.student;

public class KechengDaoImp {
    public List<course> selectAll() {
        List<course> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        DBHelper dbHelper = new DBHelper();
        try {
            conn = dbHelper.getConn();
            preparedStatement = conn.prepareStatement("select * from webdesign.course");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                course course = new course();
                course.setId(resultSet.getInt("id"));
                course.setName(resultSet.getString("name"));
                course.setTeacher(resultSet.getString("teacher"));
                course.setCredit(resultSet.getInt("credit"));
                list.add(course);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            dbHelper.closeAll(conn,preparedStatement,resultSet);
        }
return list;
    }

    public void insert(course course) {
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        DBHelper dbHelper = new DBHelper();
       conn= dbHelper.getConn();
        try {
            preparedStatement = conn.prepareStatement("insert into webdesign.course(name, teacher, credit) VALUE (?,?,?)");
            preparedStatement.setString(1,course.getName());
            preparedStatement.setString(2,course.getTeacher());
            preparedStatement.setInt(3,course.getCredit());
            int i = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            dbHelper.closeAll(conn,preparedStatement,resultSet);
        }
    }

    public void update(course course) {
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        DBHelper dbHelper = new DBHelper();
        conn= dbHelper.getConn();
        try {
            int i = conn.prepareStatement("update webdesign.course set name=?,teacher=?,credit=?").executeUpdate();
            preparedStatement.setString(1,course.getName());
            preparedStatement.setString(2,course.getTeacher());
            preparedStatement.setInt(2,course.getCredit());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            dbHelper.closeAll(conn,preparedStatement,resultSet);
        }


    }
}
